//
//  GolfFriendCircleCell.m
//  GolfFriend
//
//  Created by vescky on 13-11-30.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "GolfFriendCircleCell.h"
#import "LitePhotoCollectionView.h"
#import "UIImageView+MJWebCache.h"
#import "DateUtility.h"
#import "CommonUtility.h"
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"
#import "CircleDetailViewController.h"
#import "PersonalInfoViewController.h"
#import "SVProgressHUD.h"
#import "AppsEngine.h"
#import "UserSession.h"
#import "DXAlertView.h"
#import "CacheDaoForCircleContent.h"

@interface GolfFriendCircleCell ()<LitePhotoCollectionViewDelegate> {
    LitePhotoCollectionView *imgCollectionView;
    LitePhotoCollectionView *videoCollectionView;
    
    CircleContentVO* contentVo;
    DXAlertView *alertForDelete;
}

@end

@implementation GolfFriendCircleCell
@synthesize delegate;

- (void)setDataInfo:(CircleContentVO*)ccVO {
    bool hasContent = NO;
    NSArray *imgArr,*videoArr;
    contentVo = ccVO;
    
    if ([ccVO.userId isEqualToString:[[UserSession shareUserSession] getUserId]]) {
        btnDelete.hidden = NO;
    }
    
    if (ccVO.userId && ccVO.userId.length > 0) {
        NSString *avatarLink = ccVO.avatar;
        if ([avatarLink stringByMatching:Qiniu_Domain]) {
            avatarLink = GetQiniuResizeImageLink(avatarLink, 120);
        }
        
        [imgvAvatar setImageURLStr:avatarLink placeholder:Default_Avatar];
    }
    
    if (ccVO.userName && ccVO.userName.length > 0) {
        [labelUserName setText:ccVO.userName];
    }
    else {
        [labelUserName setText:@"匿名"];
    }
    
    if ([ccVO.isSupported intValue] == 0) {
        //not supported
        btnSupport.selected = NO;
    }
    else if ([ccVO.isSupported intValue] == 1) {
        //supported
        btnSupport.selected = YES;
    }
    else if ([ccVO.isSupported intValue] == 2) {
        //self
        btnSupport.enabled = NO;
        btnDelete.hidden = NO;
    }
    
    [labelZan setText:ccVO.zan];
    [labelCommons setText:ccVO.comments];
    [labelTime setText:getWeiboDisplayTimeFromDate(getDateFromString(@"yyyy-MM-dd HH:mm:ss", ccVO.time))];
    imgvAvatar.layer.cornerRadius = imgvAvatar.frame.size.width / 2;
    
    if (ccVO.content && ccVO.content.length > 0) {
        [labelContent setText:ccVO.content];
        hasContent = YES;
    }
    
    if (ccVO.sourceLinks && [ccVO.sourceLinks count] > 0) {
        imgArr = [ccVO.sourceLinks objectForKey:@"image"];
        videoArr = [ccVO.sourceLinks objectForKey:@"video"];
    }
    
    CGRect contentRect = labelContent.frame;
    float flexibleMargin = 5;
    
    if (!hasContent) {
        [labelContent removeFromSuperview];
        contentRect.size.height = 0;
        contentRect.origin.y = labelUserName.frame.origin.y + labelUserName.frame.size.height;
    }
    else {
        CGSize cSize = [ccVO.content sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(labelContent.frame.size.width,1000) lineBreakMode:0];
        contentRect.size.height = cSize.height >= 30 ? cSize.height : 30;
        [labelContent setFrame:contentRect];
    }
    
    CGRect viewRect = self.frame;
    if (imgArr && [imgArr count] > 0) {
        imgCollectionView = [[LitePhotoCollectionView alloc] init];
        [imgCollectionView setPhotoCollection:[[NSMutableArray alloc] initWithArray:imgArr]];
        [imgCollectionView setMargin:5.0];
        [imgCollectionView setViewWidth:contentRect.size.width - 20];//与content同宽度
        [imgCollectionView setColCount:3];
        [imgCollectionView.view setFrame:CGRectMake(contentRect.origin.x,contentRect.origin.y + contentRect.size.height + flexibleMargin , contentRect.size.width, [imgCollectionView getViewHeight])];
        [self addSubview:imgCollectionView.view];
        
        viewRect.size.height = imgCollectionView.view.frame.origin.y + imgCollectionView.view.frame.size.height + buttomView.frame.size.height + 2 * flexibleMargin;
    }
    else {
        viewRect.size.height = contentRect.origin.y + contentRect.size.height + buttomView.frame.size.height + 2 * flexibleMargin;
    }
    
    [self setFrame:viewRect];
    
}


#pragma mark - LitePhotoCollectionViewDelegate
- (void)imageDidTapped:(int)index {
    
}

#pragma mark - Button Action
- (IBAction)btnGotoDetails:(id)sender {
    if ([delegate respondsToSelector:@selector(detailConteButtonDidPress)]) {
        [delegate detailConteButtonDidPress];
    }
    
    CircleDetailViewController *vc = [[CircleDetailViewController alloc] init];
    [vc setContentVO:contentVo];
    [[APP_DELEGATE navigationController] pushViewController:vc animated:YES];
}

- (IBAction)btnAvatarPressed:(id)sender {
    if ([delegate respondsToSelector:@selector(avatarButtonDidPress)]) {
        [delegate avatarButtonDidPress];
    }
    
    PersonalInfoViewController *vc = [[PersonalInfoViewController alloc] init];
    vc.userInfo = [[NSMutableDictionary alloc] initWithDictionary:[contentVo toDictionary]];
    [[APP_DELEGATE navigationController] pushViewController:vc animated:YES];
}

- (IBAction)btnSupportPressed:(id)sender {
    if (btnSupport.selected) {
        [SVProgressHUD showErrorWithStatus:@"您已赞过!"];
        return;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:contentVo.articleId,@"articleId",@"circle",@"type",[[UserSession shareUserSession] getUserId],@"fromId", nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfPublishZan" param:params onCompletion:^(id jsonResponse) {
        NSLog(@"zan success");
        [SVProgressHUD showSuccessWithStatus:@"已赞！"];
        btnSupport.selected = YES;
        labelZan.text = [NSString stringWithFormat:@"%d",[labelZan.text intValue]+1];
        contentVo.isSupported = @"1";
        contentVo.zan = labelZan.text;
        [[CacheDaoForCircleContent shareCacheDaoForCircleContent] updateCacheDataWithCircleContent:contentVo];
    } onError:^(NSError *error) {
        
    } method:@"GET"];
    
}

- (IBAction)btnDeletePressed:(id)sender {
    __block CircleContentVO *cVo = contentVo;
    if (!alertForDelete) {
        alertForDelete = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"确认要删除此文章?" leftButtonTitle:@"删除" rightButtonTitle:@"取消"];
        alertForDelete.leftBlock = ^(void){
            NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:cVo.articleId,@"articleId",[[UserSession shareUserSession] getUserId],@"userId", nil];
            [[AppsEngine shareAppsEngine] submitRequest:@"gfDeleteCircleArticle" param:params onCompletion:^(id jsonResponse) {
                NSLog(@"delete success");
                [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Article_Deleted object:cVo];
            } onError:^(NSError *error) {
                
            } method:@"GET"];
        };
    }
    
    [alertForDelete show];
}

#pragma mark - Public Methods
- (float)getContentHeight:(CircleContentVO*)cContent {
    [self setDataInfo:cContent];
    return self.frame.size.height;
}



@end
